package com.ssm.custom.servlet;

import com.ssm.custom.anno.RequestMapping;
import com.ssm.custom.handler.InvocationHandler;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.logging.Logger;

/**
 * @author: Hsiao
 * @date: 2023-11-22
 * @description:
 */
public class HandlerMapping {

    Logger log = Logger.getLogger("com.ssm.custom.servlet.HandlerMapping");

    /**
     * 扫描controller中的方法
     * @param classSet controller
     * @return Map<url, method>
     */
    public Map<String, InvocationHandler> urlMapping(Set<Class<?>> classSet) {

        Map<String, InvocationHandler> handlerMap = new HashMap<>();

        for (Class<?> clazz : classSet) {
            String clazzReqPath = clazz.getAnnotation(RequestMapping.class).value();
            log.info("类上的请求路径为：" + clazzReqPath);

            Method[] methods = clazz.getDeclaredMethods();
            for (Method method : methods) {
                boolean hasRequestMapping = method.isAnnotationPresent(RequestMapping.class);
                if (hasRequestMapping) {
                    String methodReqPath = method.getAnnotation(RequestMapping.class).value();
                    boolean invalid = Objects.isNull(methodReqPath) || Objects.equals(methodReqPath, "");
                    methodReqPath = invalid ? "" : methodReqPath;
                    log.info("方法上的请求路径为：" + methodReqPath);

                    try {
                        InvocationHandler handler = new InvocationHandler(clazz.getConstructor().newInstance(), method);
                        handlerMap.put(clazzReqPath + methodReqPath, handler);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return handlerMap;
    }
}
